# [src/view/CourseBox.py]
from typing import List
from PySide6.QtWidgets import QVBoxLayout, QGroupBox, QPushButton, QMessageBox
from PySide6.QtCore import Qt, Signal
from model.Student import Student
from util.FileUtil import FileUtil
import openpyxl

class CourseBox(QVBoxLayout):
    students_loaded = Signal(list, list)
    random_requested = Signal()
    
    def __init__(self, title="课程"):
        super().__init__()
        self._container = QGroupBox(title)
        self._container.setLayout(self)
        self.setAlignment(Qt.AlignmentFlag.AlignHCenter)
        
        self.btn_open = QPushButton("打开文件")
        self.btn_save = QPushButton("保存记录")
        self.btn_random = QPushButton("随机选人")
        self.addWidget(self.btn_open)
        self.addWidget(self.btn_save)
        self.addWidget(self.btn_random)
        
        self._current_file_path = None  # 保存当前打开的Excel文件路径
        
        # 连接信号
        self.btn_open.clicked.connect(self.open_student_file)
        self.btn_save.clicked.connect(self.save_records)
        self.btn_random.clicked.connect(self.on_random_clicked)
    
    def open_student_file(self):
        """文件打开方法"""
        file_path = FileUtil.get_excel_path(self._container, "选择课程文件")
        if not file_path:
            return
            
        try:
            wb = openpyxl.load_workbook(file_path)
            students = FileUtil.load_students(wb["students"])
            behavior = FileUtil.load_behavior(wb["behavior"])
            self._current_file_path = file_path  # 保存当前文件路径
            self.students_loaded.emit(students, behavior)
        except Exception as e:
            print(f"文件操作失败: {e}")

    def save_records(self, students: List[Student]):
        """
        保存学生记录到文件
        :param stu_buttons: 学生按钮列表
        """
        if not self._current_file_path:
            QMessageBox.warning(
                self._container,
                "保存失败",
                "没有打开的文件，请先打开文件再保存",
                QMessageBox.StandardButton.Ok
            )
            return

        success = FileUtil.save_students_file(students, self._current_file_path)
        
        if success:
            QMessageBox.information(
                self._container,
                "保存成功",
                "学生记录已成功保存",
                QMessageBox.StandardButton.Ok
            )
        else:
            QMessageBox.warning(
                self._container,
                "保存失败",
                "保存文件时发生错误",
                QMessageBox.StandardButton.Ok
            )

    def on_random_clicked(self):
        """触发随机选人信号"""
        self.random_requested.emit()